# -*- coding: utf-8 -*-

import os
from django.utils.datastructures import MultiValueDictKeyError
from django.contrib.auth import login
from django.contrib.auth import logout
from django.contrib.sessions import *
from django.http import HttpResponse
from django.http import HttpResponseForbidden
from django.http import HttpResponseNotFound
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext, loader
from labmin.webapp.forms import *
from labmin.webapp.filters import *
from labmin.webapp.models import Admin
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from labmin.webapp.StudentDaoLDAP import *
from labmin.webapp.LDAPDataConnector import *
import ConfigParser

__ldapConfigurator = ConfigParser.ConfigParser()
__ldapConfigurator.read('config/labmin.conf')

def not_found(request):
    t = loader.get_template('404.html')
    c = RequestContext(request, {})
    return HttpResponseNotFound(t.render(c))

def forbidden(request):
    t = loader.get_template('403.html')
    c = RequestContext(request, {})
    return HttpResponseForbidden(t.render(c))

def main(request):
    return render_to_response('main.html', context_instance=RequestContext(request));

def shell(request):
    return render_to_response('shell.html', context_instance=RequestContext(request));

def login(request):
    try:
        if request.session['user']:
            return HttpResponseRedirect('/')
    except KeyError:
        pass
    try:
        username = request.POST['username']
        password = request.POST['password']
    except KeyError:
        return HttpResponseRedirect('/')
    try:
        user = Admin.objects.get(login=username)
    except:
        user = None
    if user is not None:
        if user.comparePassword(password):
            request.session['user'] = user
            return HttpResponseRedirect('/')
        else:
            return render_to_response('main.html', {
                "password_error": True
            }, context_instance=RequestContext(request));
    else:
        return render_to_response('main.html', {
            "login_error": True
        }, context_instance=RequestContext(request));

def logout(request):
    if request.session.get('user', False):
        del request.session['user']
    return HttpResponseRedirect('/')


#---- STUDENTS ----

def students_list(request):
    try:
        if request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    students = Student.objects.all()
    if request.method == 'POST':
        filtr_login = request.POST['filtr_login']
        filtr_1=StudentFilter()

        filtr = {'login' : filtr_login}
        students = filtr_1.applyFilter(filtr, students)
    return render_to_response('students_list.html', {
        'students': students
    }, context_instance=RequestContext(request));


def student_form(request, student_pk=None):
    try:
        if request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    if student_pk is not None:
        student = get_object_or_404(Student, pk=student_pk)
    else:
        student = None
    form = StudentForm(data=request.POST or None, instance=student)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/students_list')
    return render_to_response('student_form.html', {
        'form': form
    }, context_instance=RequestContext(request))


def show_student(request, student_pk):
    try:
        if request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')

    connector = LDAPDataConnector(__ldapConfigurator)
    LDAPsearcher = StudentDaoLDAP(connector, __ldapConfigurator)

    student = Student.objects.get(pk=student_pk)
    LDAPstudent = LDAPsearcher.searchStudent(student.email)
    
    LDAPstudent[0][1]['cn'][0] = unicode(LDAPstudent[0][1]['cn'][0])
    LDAPstudent[0][1]['mail'] = unicode(LDAPstudent[0][1]['mail'][0])
    LDAPstudent[0][1]['faculty'] = unicode(LDAPstudent[0][1]['faculty'][0])
    LDAPstudent[0][1]['year'] = unicode(LDAPstudent[0][1]['year'][0])

    return render_to_response('show_student.html', {
        'student':LDAPstudent[0][1],
        'student_groups':student.studentgroup_set.all()
    }, context_instance=RequestContext(request))


def delete_students(request):
    try:
        if request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')

    list = request.POST.getlist('list')
    if request.method == 'POST':
        for student_pk in list:
            student = get_object_or_404(Student, pk=student_pk)
            student.delete()
        return HttpResponseRedirect('/students_list')
    return not_found(request)


#---- STUDENT GROUPS ----

def student_groups_list(request):
    try:
        if request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    student_groups = StudentGroup.objects.all()
    paginator = Paginator(student_groups, 4)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        student_groups = paginator.page(page)
    except (EmptyPage, InvalidPage):
        student_groups = paginator.page(paginator.num_pages)

    return render_to_response('student_groups_list.html', {
        'student_groups': student_groups
    }, context_instance=RequestContext(request))


def student_group_form(request, student_group_pk=None):
    try:
        if request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    if student_group_pk is not None:
        student_group = get_object_or_404(StudentGroup, pk=student_group_pk)
    else:
        student_group = None
    form = StudentGroupForm(data=request.POST or None, instance=student_group, auto_id = False)

    if request.method == 'POST':
        if not request.POST.getlist('list'):
            if form.is_valid():
                student_group = form.save()
                return HttpResponseRedirect('/student_groups_list')
        else:	#jeśli przekazujemy listę studentów, z których tworzymy grupę
            data = {'students': request.POST.getlist('list')}
            form = StudentGroupForm(initial={'students':request.POST.getlist('list')}, auto_id = False)
    return render_to_response('student_form.html', {
        'form': form,
    }, context_instance=RequestContext(request))


def delete_student_group(request, student_group_pk):
    try:
        if request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    #if request.method == 'POST':
    student_group = get_object_or_404(StudentGroup, pk=student_group_pk)
    student_group.delete()
    return HttpResponseRedirect('/student_groups_list')
    #return not_found(request)


#---- ADMINS ----

def admins_list(request):
    try:
        if not request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    admins = Admin.objects.all()

    paginator = Paginator(admins, 4)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        admins = paginator.page(page)
    except (EmptyPage, InvalidPage):
        admins = paginator.page(paginator.num_pages)
    
    return render_to_response('admins_list.html', {
        'admins': admins
    }, context_instance=RequestContext(request))


def admin_form(request, admin_pk=None):
    try:
        if not request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    if admin_pk is not None:
        admin = get_object_or_404(Admin, pk=admin_pk)
    else:
        admin = None
    form = AdminForm(data=request.POST or None, instance=admin)
    if request.method == 'POST' and form.is_valid():
        admin = form.save(commit=False)
        admin.setPassword(form.data['password'])
        admin.save()
        form.save_m2m()
        return HttpResponseRedirect('/admins_list')
    return render_to_response('student_form.html', {
        'form': form,
    }, context_instance=RequestContext(request))


def show_admin(request, admin_pk):
    try:
        if not request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    admin = Admin.objects.get(pk=admin_pk)
    return render_to_response('show_admin.html', {
        'admin': admin
    }, context_instance=RequestContext(request))


def delete_admin(request, admin_pk):
    try:
        if not request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    admin = get_object_or_404(Admin, pk=admin_pk)
    admin.delete()
    return HttpResponseRedirect('/admins_list')


#---- SERVICES ----

def services_list(request):
    try:
        if not request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    services = Service.objects.all()

    paginator = Paginator(services, 4)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        services = paginator.page(page)
    except (EmptyPage, InvalidPage):
        services = paginator.page(paginator.num_pages)
    
    return render_to_response('services_list.html', {
        'services': services
    }, context_instance=RequestContext(request))


def service_form(request, service_pk=None):
    try:
        if not request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    if service_pk is not None:
        service = get_object_or_404(Service, pk=service_pk)
    else:
        service = None
    form = ServiceForm(data=request.POST or None, files=request.FILES or None, instance=service)
    if request.method == 'POST' and form.is_valid():
        try:
            script_file = request.FILES['script_file']
        except MultiValueDictKeyError:
            script_file = None
        if script_file is not None:
            if service and service.script_file and os.path.exists(service.script_file.path):
                os.remove(service.script_file.path)
        form.save()
        return HttpResponseRedirect('/services_list')
    return render_to_response('student_form.html', {
        'form': form
    }, context_instance=RequestContext(request))


def delete_service(request, service_pk):
    try:
        if not request.session['user'].is_superadmin:
            return forbidden(request)
    except KeyError:
        return HttpResponseRedirect('/')
    service = get_object_or_404(Service, pk=service_pk)
    service.delete()
    if service.script_file and os.path.exists(service.script_file.path):
        os.remove(service.script_file.path)
    return HttpResponseRedirect('/services_list')

